package com.my.socket.nio.v8;

import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;

/**
 * Created by Scarlett on 2018/7/2 0002.
 */
public class ServerDispatcher {
    private ServerSocketChannel serverSocketChannel;
    private Selector[] selectors = new Selector[3];

    public ServerDispatcher(ServerSocketChannel serverSocketChannel, SelectorProvider provider) throws Exception {
        this.serverSocketChannel = serverSocketChannel;
        for (int i = 0; i < 3; i++) {
            this.selectors[i] = provider.openSelector();
        }
    }

    public void execute() throws Exception {
        SocketAcceptHandler acceptHandler = new SocketAcceptHandler(this, serverSocketChannel, selectors[0]);
        new Thread(acceptHandler).start();

        SocketReadHandler readHandler = new SocketReadHandler(this, serverSocketChannel, selectors[1]);
        new Thread(readHandler).start();

        SocketWriteHandler writeHandler = new SocketWriteHandler(this, serverSocketChannel, selectors[2]);
        new Thread(writeHandler).start();
    }

    public Selector getReadSelector() {
        return selectors[1];
    }

    public Selector getWriteSelector() {
        return selectors[2];
    }
}
